# -*- coding: utf-8 -*-
from myquerybuilder import QueryBuilder

class DBExporter:
    ptengine_export_enable = 'ptengine.export.export_enable'
    ptengine_export_db_config = 'ptengine.export.db_config'

    def __init__(self, config):
        if not config.get_param(DBExporter.ptengine_export_enable) == 'True':
            self.exportEnabled = False
            return
        self.exportEnabled = True

        options = eval(config.get_param(DBExporter.ptengine_export_db_config))
        self.qb = QueryBuilder(**options)

    def Export(self, model, vals):
        if not self.exportEnabled:
            return

        self.qb.begin()
        try:
            for k,v in model.getExportFields(vals).items():
                where = model.getExportConstraint(k)
                affected = self.qb.update(k,v, where)
            self.qb.commit()
        except:
            self.qb.rollback()
            raise